package com.atguigu.gulimall.product.config;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.io.IOException;

/**
 * @Author 小坏
 * @Date 2020/11/5 13:46
 * @Version 1.0
 * @program: 父工程 gulimall 万物起源之地
 */

//ttl时间失效、原因是使用的是自己配置redisCacheConfiguration
    //需要绑定 CacheProperties.class
@EnableConfigurationProperties(CacheProperties.class)
@EnableCaching  //开启缓存
@Configuration
public class MyCacheConfig {

    /**
     * 第一种使用
     *    @Autowired
     *     CacheProperties cacheProperties;
     *
     *     第二种使用放到方法里面
     */
    @Autowired
    CacheProperties cacheProperties;

    /**
     * 配置文件中的东西没有用上
     * 1、原来和配置文件绑定的配置类是这个样子的
     *     @ConfigurationProperties(prefix = "spring.cache")
     * public class CacheProperties {
     *
     * 2、要让他生效
     * @EnableConfigurationProperties(CacheProperties.class)
     * @return
     */
    @Bean //方法穿的所有东西、他都会都会从
    public RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){

        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        config = config.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));

        CacheProperties.Redis redisProperties = cacheProperties.getRedis();
        if (redisProperties.getTimeToLive() != null) {
            config = config.entryTtl(redisProperties.getTimeToLive());
        }
        if (redisProperties.getKeyPrefix() != null) {
            config = config.prefixKeysWith(redisProperties.getKeyPrefix());
        }
        if (!redisProperties.isCacheNullValues()) {
            config = config.disableCachingNullValues();
        }
        if (!redisProperties.isUseKeyPrefix()) {
            config = config.disableKeyPrefix();
        }

        return config;
    }



}
